package com.eve.eplus.main.Fragment;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.eve.eplus.R;
import com.eve.eplus.common.app.BaseApplication;
import com.eve.eplus.common.app.Configuration;
import com.eve.eplus.common.app.Constants;
import com.eve.eplus.common.app.SettingConstants;
import com.eve.eplus.common.tools.ComImgTools;
import com.eve.eplus.common.tools.ComTimeTools;
import com.eve.eplus.common.tools.LogTools;
import com.eve.eplus.common.view.ComDialogTools;
import com.eve.eplus.common.view.ComToastTools;
import com.eve.eplus.main.HomeActivity;
import com.eve.eplus.main.SendMsgActivity;
import com.eve.eplus.main.logic.SettingUtility;

/**
 * 一键享微博页面
 * 
 * @author norsie
 * @create 13-04-07
 * 
 */
public class ShareFragment extends Fragment
{
    private LinearLayout btnSend, btnVoice, btnPic, btnTrends, btnClean;
    private EditText edtContent;
    private TextView tvNum;
    private LayoutInflater inflater;
    private Dialog mDialog;

    private String picPath;// 图片文件路径
    private static final int PHOTO_WITH_CAMERA = 1010;// 拍摄照片
    private static final int PHOTO_WITH_DATA = 1020;// 从SD中得到照片
    private static final File PHOTO_DIR = new File(Configuration.PHOTO_DIR);// 拍摄照片存储的文件夹路劲
    private File captureFile;// 拍摄的照片文件

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState)
    {
        // TODO Auto-generated method stub
        this.inflater = inflater;
        View view = inflater.inflate(R.layout.activity_home_share_main, null);
        initView(view);
        return view;
    }

    private void initView(View view)
    {
        btnSend = (LinearLayout) view.findViewById(R.id.send);
        btnVoice = (LinearLayout) view.findViewById(R.id.voice);
        btnPic = (LinearLayout) view.findViewById(R.id.pic);
        btnTrends = (LinearLayout) view.findViewById(R.id.call);
        btnClean = (LinearLayout) view.findViewById(R.id.cleanAll);
        edtContent = (EditText) view.findViewById(R.id.edittext);
        tvNum = (TextView) view.findViewById(R.id.editNum);

        btnSend.setOnClickListener(onClickListener);
        btnVoice.setOnClickListener(onClickListener);
        btnPic.setOnClickListener(onClickListener);
        btnTrends.setOnClickListener(onClickListener);
        btnClean.setOnClickListener(onClickListener);
        edtContent.addTextChangedListener(textWatcher);
    }

    /**
     * 文字变化监听事件
     */
    TextWatcher textWatcher = new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count)
        {
            // TODO Auto-generated method stub
            int len = edtContent.getText().toString().length();
            String slen = String.valueOf(140 - len);
            tvNum.setText(slen);
            if (140 - len <= 0)
            {
                tvNum.setTextColor(Color.RED);
                /********************************** 设置发送按钮为灰色或者其他 **********************************************/
            }
            else
            {
                tvNum.setTextColor(Color.DKGRAY);
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after)
        {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable s)
        {
            // TODO Auto-generated method stub

        }
    };

    /**
     * 按钮点击监听事件
     */
    OnClickListener onClickListener = new OnClickListener() {

        @Override
        public void onClick(View v)
        {
            switch (v.getId())
            {
                case R.id.send:
                    send();
                    break;

                case R.id.voice:

                    break;

                case R.id.pic:
                    getPic();
                    break;

                case R.id.call:

                {
                    int index = edtContent.getSelectionStart();
                    Editable edit = edtContent.getEditableText();// 获取EditText的文字
                    if (index < 0 || index >= edit.length())
                    {
                        edit.append("##");
                    }
                    else
                    {
                        edit.insert(index, "##");// 光标所在位置插入文字
                    }
                    edtContent.setSelection(edit.length() - 1);
                }
                    break;
                case R.id.cleanAll:

                    ComDialogTools.showConfirmDialog(getActivity(), "提示", "清空",
                            "取消", "确认清空文字内容？",
                            new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog,
                                        int which)
                                {
                                    // TODO Auto-generated method stub
                                    edtContent.setText("");
                                    dialog.dismiss();
                                }
                            }, new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog,
                                        int which)
                                {
                                    // TODO Auto-generated method stub
                                    dialog.dismiss();
                                }
                            });
                    break;
                default:
                    break;
            }

        }
    };

    /**
     * 发送微博
     */
    protected void send()
    {
        Animation cycleAnim = AnimationUtils.loadAnimation(getActivity(),
                R.anim.sendbtn_anim);
        String content = edtContent.getText().toString();
        if (content.length() == 0 && picPath != null)
            content = "分享图片";
        if (content.length() > 140)
        {
            btnSend.startAnimation(cycleAnim);
            ComToastTools.ShowMsg(getActivity(), "已超过"
                    + (content.length() - 140) + "个字", "l");
        }
        else if (content.length() == 0)
        {
            btnSend.startAnimation(cycleAnim);
            ComToastTools.ShowMsg(getActivity(), "请输入微博内容", "l");
        }
        else
        {

            Intent intent = new Intent(getActivity(), SendMsgActivity.class);
            intent.putExtra(Constants.SNS_SEND_CONTENT, content);
            intent.putExtra(Constants.SNS_SEND_PICURI, picPath);
            startActivity(intent);
        }

    }

    /**
     * 获取图片
     */
    protected void getPic()
    {
        View layout = inflater.inflate(R.layout.activity_home_share_takepic,
                (ViewGroup) getActivity().findViewById(R.id.dialog));
        layout.findViewById(R.id.iv_data).setOnClickListener(
                onClickListenerInDialog);
        layout.findViewById(R.id.iv_camera).setOnClickListener(
                onClickListenerInDialog);
        mDialog = new Dialog(getActivity(), R.style.dialog);
        mDialog.setContentView(layout);
        mDialog.show();

    }

    /**
     * 对话框的点击事件
     */
    OnClickListener onClickListenerInDialog = new OnClickListener() {

        @Override
        public void onClick(View v)
        {
            switch (v.getId())
            {
                case R.id.iv_camera:
                    String status = Environment.getExternalStorageState();
                    if (status.equals(Environment.MEDIA_MOUNTED))
                    {// 判断是否有SD卡
                        Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        captureFile = new File(
                                               PHOTO_DIR,
                                               ComTimeTools.getTime("'IMG'_yyyyMMdd_HHmmss")
                                                       + ".jpg");
                        try
                        {
                            if(SettingUtility.getCameraSaveSetting()==SettingConstants.CAMERA_SAVE_TRUE)
                            captureFile.createNewFile();
                            i.putExtra(MediaStore.EXTRA_OUTPUT,
                                    Uri.fromFile(captureFile));// 将拍摄的照片信息存到capturefile中
                        }
                        catch (IOException e)
                        {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

                        startActivityForResult(i, PHOTO_WITH_CAMERA);// 用户点击了从照相机获取
                    }
                    else
                    {
                        ComToastTools.ShowMsg(getActivity(), "没有SD卡", "l");
                    }
                    break;

                case R.id.iv_data:
                    Intent intent = new Intent();
                    /* 开启Pictures画面Type设定为image */
                    intent.setType("image/*");
                    /* 使用Intent.ACTION_GET_CONTENT这个Action */
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                    /* 取得相片后返回本画面 */
                    startActivityForResult(intent, PHOTO_WITH_DATA);
                    break;
                default:
                    break;
            }

            mDialog.dismiss();
        }
    };

    public void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        File file = null;
        Bitmap pic = null;
        if (resultCode == FragmentActivity.RESULT_OK)
        {
            switch (requestCode)
            {
                case PHOTO_WITH_CAMERA:// 获取拍摄的文件
                    picPath = captureFile.getAbsolutePath();
                    LogTools.info("PicPath:" + picPath);
                    file = new File(picPath);
                    pic = ComImgTools.decodeFile(file);
                    // thumbimage.setImageBitmap(pic);
                    LogTools.info("PicFrom:相机");
                    break;

                case PHOTO_WITH_DATA:// 获取从图库选择的文件
                    Uri uri = data.getData();
                    String scheme = uri.getScheme();
                    if (scheme.equalsIgnoreCase("file"))// miui的返回类型
                    {
                        picPath = uri.getPath();
                        LogTools.info("PicPath:" + picPath);
                        LogTools.info("PicFrom:文件,MIUI");
                        file = new File(picPath);
                        pic = ComImgTools.decodeFile(file);
                        // thumbimage.setImageBitmap(pic);
                    }
                    else if (scheme.equalsIgnoreCase("content"))// 原生的返回类型
                    {
                        Cursor cursor = getActivity().getContentResolver().query(
                                uri, null, null, null, null);
                        cursor.moveToFirst();
                        picPath = cursor.getString(1);
                        file = new File(picPath);
                        pic = ComImgTools.decodeFile(file);
                        LogTools.info("PicPath:" + picPath);
                        LogTools.info("PicFrom:文件,原生");
                        // thumbimage.setImageBitmap(pic);
                    }
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    };
}
